/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.prod.mrp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.prod.bom.service.ProdBomHeadService;
import com.erp.prod.mps.dao.model.ProdMpsHead;
import com.erp.prod.mps.dao.model.ProdMpsHeadCO;
import com.erp.prod.mps.dao.model.ProdMpsLine;
import com.erp.prod.mps.service.ProdMpsHeadService;
import com.erp.prod.mps.service.ProdMpsLineService;
import com.erp.prod.mrp.dao.model.ProdMrpHead;
import com.erp.prod.mrp.dao.model.ProdMrpHeadCO;
import com.erp.prod.mrp.service.ProdMrpHeadService;
import com.erp.prod.mrp.service.ProdMrpLineService;

@Controller
@RequestMapping("/web/prodMrpHead")
public class ProdMrpHeadWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ProdMrpHeadWebController.class);
    
    //服务层注入
    @Autowired
    private ProdMrpHeadService prodMrpHeadService;
    @Autowired
    private ProdMrpLineService prodMrpLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private ProdMpsHeadService prodMpsHeadService;
    @Autowired
    private ProdMpsLineService prodMpsLineService;
    @Autowired
    private ProdBomHeadService prodBomHeadService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getProdMrpHeadList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-11-18 16:26:52
     * @author 
     * @param pages
     * @param prodMrpHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdMrpHeadList")
    public String getProdMrpHeadList(Pages pages, ProdMrpHeadCO prodMrpHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<ProdMrpHead> prodMrpHeadList = this.prodMrpHeadService.getDataObjectsForDataAuth("", pages, prodMrpHeadCO);
        
        //循环设置显示字段
        for(ProdMrpHead prodMrpHead: prodMrpHeadList) {
            prodMrpHead.setStaffName(this.hrCommonService.getHrStaff(prodMrpHead.getStaffCode()).getStaffName());
            prodMrpHead.setDepartmentName(this.hrCommonService.getHrDepartment(prodMrpHead.getDepartmentCode()).getDepartmentName());
        }
        
        //入库状态
        Map statusMap = RDDataBox.getStatusMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //物料Map
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        
        //页面属性设置
        model.addAttribute("prodMrpHeadList", prodMrpHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("statusMap", statusMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("materialMap", materialMap);
        
        return "basic.jsp?content=prodMrp/prodMrpList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-11-18 16:26:52
     * @author 
     * @param prodMrpHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdMrpHead")
    public String getProdMrpHead(ProdMrpHead prodMrpHead, Model model) {
        //状态
        Map statusMap = RDDataBox.getStatusMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        
        //查询要编辑的数据
        if(prodMrpHead!=null&&StringUtils.isNotBlank(prodMrpHead.getMrpHeadCode())) {
            //获取头信息
            ProdMrpHead prodMrpHeadTemp = this.prodMrpHeadService.getDataObject(prodMrpHead.getMrpHeadCode());
            if(prodMrpHeadTemp!=null) {
                prodMrpHead = prodMrpHeadTemp;
            }
            
            //设置显示字段
            prodMrpHead.setStaffName(this.hrCommonService.getHrStaff(prodMrpHead.getStaffCode()).getStaffName());
            prodMrpHead.setDepartmentName(this.hrCommonService.getHrDepartment(prodMrpHead.getDepartmentCode()).getDepartmentName());
        }else {
            //初始化默认字段
            prodMrpHead.setStatus("NEW");
            
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            prodMrpHead.setStaffCode(staffInfo.getStaffCode());
            prodMrpHead.setDepartmentCode(staffInfo.getDepartmentCode());
            prodMrpHead.setStaffName(staffInfo.getStaffName());
            prodMrpHead.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        //页面属性设置
        model.addAttribute("prodMrpHead", prodMrpHead);
        model.addAttribute("statusMap", statusMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        
        return "basic.jsp?content=prodMrp/prodMrpEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-11-18 16:26:52
     * @author 
     * @param prodMrpHead
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editProdMrpHead")
    public String editProdMrpHead(@Valid ProdMrpHead prodMrpHead, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getProdMrpHead";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.prodMrpHeadService.insertOrUpdateDataObject(prodMrpHead);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("mrpHeadCode", prodMrpHead.getMrpHeadCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "计划编码已存在，请重新输入");
                return "redirect:getProdMrpHeadList";
            }else {
                throw e;
            }
        }
        
        return "redirect:getProdMrpHead";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-11-18 16:26:52
     * @author 
     * @param prodMrpHead
     * @return String
     *
     */
    @RequestMapping("deleteProdMrpHead")
    public String deleteProdMrpHead(ProdMrpHead prodMrpHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if(prodMrpHead!=null&&prodMrpHead.getMrpHeadId()!=null) {
            if(prodMrpHead.getStatus().equals("NEW")||prodMrpHead.getStatus().equals("ALTER")) {
                //删除数据
                this.prodMrpHeadService.deleteDataObject(prodMrpHead);
                
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态的MPS不能删除");
            }
        }
        
        return "redirect:getProdMrpHeadList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {
            if(approveStatus.equals("UNSUBMIT")) {
            }
            
            //更新审核状态
            this.prodMrpHeadService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("mrpHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("mrpHeadCode", code);
        }
        
        return "redirect:getProdMrpHead";
    }
    
    
    
    /**
     * 
     * @description 获取选择单据Modal
     * @date 2020年7月29日
     * @author dongbin
     * @param businessType
     * @param pages
     * @param poHeadCO
     * @param receiptHeadCO
     * @param model
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectBillModal")
    public String getSelectBillModal(String businessType, Pages pages, ProdMpsHeadCO prodMpsHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        prodMpsHeadCO.setStatus("CONFIRM");
        List<ProdMpsHead> prodMpsHeadList = this.prodMpsHeadService.getMpsListForMrp(pages, prodMpsHeadCO);
        //循环设置职员和组织信息
        for(ProdMpsHead prodMpsHead: prodMpsHeadList) {
            prodMpsHead.setStaffName(this.hrCommonService.getHrStaff(prodMpsHead.getStaffCode()).getStaffName());
            prodMpsHead.setDepartmentName(this.hrCommonService.getHrDepartment(prodMpsHead.getDepartmentCode()).getDepartmentName());
        }
        
        //状态
        Map statusMap = RDDataBox.getStatusMap();
        
        //页面属性设置
        model.addAttribute("prodMpsHeadList", prodMpsHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("statusMap", statusMap);
        
        return "prodMrp/pop/selectMpsBillModal";
    }
    
    
    
    /**
     * 
     * @description 自动创建MRP
     * @date 2020年11月19日
     * @author dongbin
     * @param billHeadCode
     * @param model
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreateMrp")
    @ResponseBody
    public String autoCreateMrp(String billHeadCode, Model model, RedirectAttributes attr) {
        //判断参数
        if(StringUtils.isNotBlank(billHeadCode)) {
            try {
                //循环验证主生产计划行物料的BOM结构
                List<ProdMpsLine> prodMpsLineList = this.prodMpsLineService.getProdMpsLineListByMpsHeadCode(billHeadCode);
                //循环计划行
                for(ProdMpsLine prodMpsLine: prodMpsLineList) {
                    Map<String, String> materialMap = new HashMap<String, String>();
                    Map<String, String> validateResultMap = new HashMap<String, String>();
                    validateResultMap.put("validateResult", "");
                    String validateResult = this.prodBomHeadService.validateBom(materialMap, prodMpsLine.getMaterialCode(), "", validateResultMap);
                    if(StringUtils.isNotBlank(validateResult)) {
                        return JsonDataUtil.getExecuteJson(-1, validateResult);
                    }
                }
                
                //调用自动创建方法
                return this.prodMrpHeadService.autoCreateMrp(billHeadCode);
            }catch(Exception e) {
                return JsonDataUtil.getExecuteJson(-1, "自动生成MRP执行错误");
            }
        }else {
            return JsonDataUtil.getExecuteJson(-1, "参数传递错误");
        }
    }
}
